package com.dianning.comm;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.*;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.util.RequestUtils;

import com.dianning.web.servlet.UserSession;

public class DianningUtil {
	
	public static UserSession getUser(HttpServletRequest request){
		return (UserSession) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
	}
	
	/**
	 * @param uid
	 * @return String
	 * 根据用户id生成照片路径，返回目录的真实路径
	 */
	public static String mkDirById(long id,String picPath){
		String[] dir = getDirById(id);
		String path = Constant.ROOTPATH + "/" + picPath + "/" + dir[0] + "/" + dir[1] + "/" + dir[2];
		File f = new File(path);
		if(!f.exists()){
			f.mkdirs();
		}
		return path;
	}
	
	public static String mkDirByNow(String picPath){
		String path = picPath + "/" + formatDateTime(new Date(),"yyyyMMdd");
		File f = new File(Constant.ROOTPATH + "/" + path);
		if(!f.exists()){
			f.mkdirs();
		}
		return path;
	}
	
	/**
	 * @param uid
	 * @return String[]
	 * 根据用户id生成照片目录
	 */
	public static String[] getDirById(long id){
		String s = formatId(id);	//格式化字符串成9位,前补0(000000001)
		String dir1 = s.substring(0, 3);	//前取3位
		String dir2 = s.substring(3, 5);	//取3-5
		String dir3 = s.substring(5, 7);	//取5-7
		String dir4 = s.substring(7);	//取最后三位
		String[] dir = new String[4];
		dir[0] = dir1;
		dir[1] = dir2;
		dir[2] = dir3;
		dir[3] = dir4;
		return dir;
	}	
	
	private static String formatId(long id){
		String s = String.valueOf(id);
		int l = s.length();
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<9-l;i++){
			sb.append("0");
		}
		sb.append(s);
		return sb.toString();
	}
	
	public static boolean isAllowPicFile(String fileName) {
		String[] filExts = { "jpg", "jpeg", "gif" };
		return FilenameUtils.isExtension(fileName, filExts);
	}
	
	public static String formatDateTime(Date date, String format) {
		SimpleDateFormat outFormat = new SimpleDateFormat(format);
		return outFormat.format(date);
	}
	
	public static String filterKeyword(String text){
		String keywords = "法轮|政府|共产党|党中央|主席|政策|集中营|大法|迫害|毛泽东|邓小平|江泽民|胡锦涛|温家宝|朱榕基|李鹏|屠杀|镇压|国务院|公安部|腐败|贪污|独裁|专制|民主|人权|文革|文化大革命|李洪志|共铲党|九评|退党|明慧|大纪元|天安门事件|军委主席|中纪委|民运|西藏|藏独|北京之春|暴乱|暴动|达赖|大参考|大纪元|动态网|专政|一言堂|官商勾结|反共|反华|疆独|六四事件|真善忍|成人玩具|性保健|成人用品|六合彩|成人网站|成人文学|成人电影|成人影视|成人图片|成人漫画|成人论坛|铃声下载|手机铃声|春药|催眠香水|催情口香糖|催情巧克力|催情药|催情药品|傻逼|你妈|操你|处女膜|轮奸|阴茎|迷奸|换妻|淫荡|口交|鸡巴|乳房|傻逼|傻b|性虐待|小穴|浪穴|阴穴|嫩穴|操穴|美穴|骚穴|浪屄|肛交|鸡奸|操岳|操逼|阴唇|阴蒂|性交|女殖器|自慰|阴道|射精|赌博|赌具|透视眼镜|卖发票|餐饮发票|住宿发票|枪支买卖|枪支供应|枪支销售|高仿|fuck|damn|shit|cocksucker|motherfucker|pussy|cunt|asshole|fuckhead|fuckface|shitface|asshole cleaner|fucking bitch|tits|god damn whore|clit|twat|bastard|bitch|whore|slut|dog|jackass|prostitute|hooker|call girl|damn it|screw|bulldager|lessy|bullshit|queer|fag|cum|piss|anus|goddamn|go to hell|prick|suck|blow job|crap|nigger|son of a bitch|pecker|scoundrel|devil|cur|poisonous|silly|fool|foolish|malicious|gall|lousy|nousea|untouchable|doggone|doggery|dub|thickhead|dolt";
		String[] words = keywords.split("[|]");
		for (int i = 0; i < words.length; i++) {
			text = text.replaceAll(words[i], "*");
		}
		return text;
	}
	
	public static String getActionMappingNameWithoutPrefix(String action) {
		String value = action;
		int question = action.indexOf("?");
		if (question >= 0) {
			value = value.substring(0, question);
		}
		int slash = value.lastIndexOf("/");
		int period = value.lastIndexOf(".");
		if ((period >= 0) && (period > slash)) {
			value = value.substring(0, period);
		}
		return (value);
	}
	
	public static String getActionMappingURLWithoutPrefix(String action) {

		StringBuffer value = new StringBuffer();

		// Use our servlet mapping, if one is specified
		String servletMapping = Constant.SERVLET_MAPPING;
		if (servletMapping != null) {

			String queryString = null;
			int question = action.indexOf("?");
			if (question >= 0) {
				queryString = action.substring(question);
			}
			String actionMapping = getActionMappingNameWithoutPrefix(action);
			if (servletMapping.startsWith("*.")) {
				value.append(actionMapping);
				value.append(servletMapping.substring(1));
			} else if (servletMapping.endsWith("/*")) {
				value.append(servletMapping.substring(0, servletMapping.length() - 2));
				value.append(actionMapping);
			} else if (servletMapping.equals("/")) {
				value.append(actionMapping);
			}
			if (queryString != null) {
				value.append(queryString);
			}
		}
		return (value.toString());
	}
	
	public static String getActionMappingName(String action) {
		String value = action;
		int question = action.indexOf("?");
		if (question >= 0) {
			value = value.substring(0, question);
		}
		int slash = value.lastIndexOf("/");
		int period = value.lastIndexOf(".");
		if ((period >= 0) && (period > slash)) {
			value = value.substring(0, period);
		}
		if (value.startsWith("/")) {
			return (value);
		} else {
			return ("/" + value);
		}
	}
	
	public static String getActionMappingURL(String action, HttpServletRequest request) {

		StringBuffer value = new StringBuffer(request.getContextPath());

		// Use our servlet mapping, if one is specified
		String servletMapping = Constant.SERVLET_MAPPING;
		if (servletMapping != null) {
			String queryString = null;
			int question = action.indexOf("?");
			if (question >= 0) {
				queryString = action.substring(question);
			}
			String actionMapping = getActionMappingName(action);
			if (servletMapping.startsWith("*.")) {
				value.append(actionMapping);
				value.append(servletMapping.substring(1));
			} else if (servletMapping.endsWith("/*")) {
				value.append(servletMapping.substring(0, servletMapping.length() - 2));
				value.append(actionMapping);
			} else if (servletMapping.equals("/")) {
				value.append(actionMapping);
			}
			if (queryString != null) {
				value.append(queryString);
			}
		}

		// Otherwise, assume extension mapping is in use and extension is
		// already included in the action property
		else {
			if (!action.startsWith("/")) {
				value.append("/");
			}
			value.append(action);
		}

		// Return the completed value
		return (value.toString());
	}
	
	public static String encodeAuth(long uid){
		String auth = String.valueOf(uid);
		auth = Util.base64Encode(auth);
		//auth = new sun.misc.BASE64Encoder().encode(auth.getBytes());
		return auth;
	}
	
	public static long decodeAuth(String auth){
		auth = Util.base64decode(auth);
		if(StringUtils.isNumeric(auth)){
			return Long.parseLong(auth);
		}else{
			return 0;
		}
		
	}
}
